<template>
  <div
      class="add-commodity"
      v-infinite-scroll="()=>{}"
      infinite-scroll-distance="10"
      :infinite-scroll-disabled="true"
  >
    <el-form :model="commodityForm" ref="commodityFormRef" label-width="120px">
      <el-form-item label="商品图片">
        <el-upload
            class="uploadGoodsP"
            :action="staticResourcesUrl+'/commodity/uploadImg'"
            ref="uploadRef"
            :auto-upload="false"
            :multiple="true"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="handChange"
            list-type="picture-card"
            :file-list="imgList"
        >
          <el-icon><plus /></el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img :src="dialogImageUrl" alt="Preview Image" style="max-width: 40vw;max-height: 40vh" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="商品名称" prop="commodityName" >
        <el-input
            v-model.trim="commodityForm.commodityName"
            placeholder="请输入您要上架的商品名称"
            :clearable="true"
            maxlength="32"
            show-word-limit
        />
      </el-form-item>
      <el-form-item label="商品类型">
        <el-select v-model="commodityForm.commodityType" placeholder="请选择" >
          <el-option
              v-for="item in commodityTypeList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品单价" porop="price">
        <el-input-number clearable="true" v-model="commodityForm.price" :precision="2" :step="1.0" :min="0" :max="999.99" />
      </el-form-item>
      <el-form-item label="商品数量" porop="count">
        <el-input-number clearable="true" v-model="commodityForm.count" :precision="0" :step="1" :min="0" :max="999" />
      </el-form-item>
      <el-form-item label="商品描述" porop="describe">
        <el-input
            v-model="commodityForm.describe"
            type="textarea"
            placeholder="为您即将上架的商品做一个简要的描述"
            :clearable="true"
            maxlength="255"
            show-word-limit
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交信息</el-button>
        <el-button type="danger" @click="resetForm">重置表单</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {ref, reactive, getCurrentInstance} from 'vue'
import request from "@/http/request";

export default {
  name: "AddCommodity",
  data() {
    return {
      commodityTypeList: [],
      commodityID: "",
      imgList: [],
      commodityFormRef: ref(null),
      dialogImageUrl: "",
      dialogVisible: false,
      commodityForm: reactive({
        commodityName: "",
        commodityType: "",
        describe: "",
        price:0,
        count:0,
      }),
    }
  },
  methods: {
    getCommodityType() {
      request({
        url: "/commodity/getCommodityType",
        method: "get",
      }).then((response) => {
        if (response.code === 200) {
          this.commodityTypeList = response.data;
        } else {
          this.$tipUtil.errTip(response.msg);
        }
      })
    },
    handlePictureCardPreview(uploadFile) {
      this.dialogImageUrl = uploadFile.url
      this.dialogVisible = true
    },
    handleRemove(uploadFile){
      if (uploadFile.img) {
        request({
          url: "/commodity/deleteImg",
          method: "post",
          data: {
            fileName: uploadFile.img.substring(uploadFile.img.lastIndexOf("/")+1),
          },
        }).then((response) => {
          if (response.code === 200) {
            this.$tipUtil.successTip(response.msg);
          } else {
            this.$tipUtil.errTip(response.msg);
          }
        })
      }
    },
    handChange(UploadFile, UploadFiles) {
      if (UploadFile.raw) {
        const isJPG = UploadFile.raw.type === 'image/jpg';
        const isJPEG = UploadFile.raw.type === 'image/jpeg';
        const isPNG = UploadFile.raw.type === 'image/png';
        const isSizeLt = UploadFile.raw.size / 1024 / 1024 < 20;
        if (!isJPG && !isJPEG && !isPNG) {
          this.$message.error('上传头像图片只能是 jpg/jpeg/png 格式!');
          UploadFiles.splice(UploadFiles.indexOf(UploadFile), 1);
        }
        if (!isSizeLt) {
          this.$message.error('上传头像图片大小不能超过 20MB!');
          UploadFiles.splice(UploadFiles.indexOf(UploadFile), 1);
        }
      }
    },
    submitUpload() {
      const _this = this;
      if (_this.commodityID!==""){
        const formData = new FormData();
        // 你可以使用FormData.append来添加键/值对到表单里面；
        _this.imgList.forEach((file) => {
          if (file.raw) {
            formData.append('file', file.raw);
          }
        })
        formData.append("uuid", _this.commodityID);
        request({
          "url": "commodity/uploadImg",
          "method": "post",
          data: formData,
        }).then( (response)=> {
          if (response.code === 200) {
            _this.$tipUtil.successTip(response.msg);
            this.$router.replace({
              name: 'ManageCommodity',
            })
          } else if (response.code === 521) {
            _this.$tipUtil.warningTip(response.msg);
          } else {
            _this.$tipUtil.errTip(response.msg);
          }
        })
      }
    },
    resetForm: function() {
      this.$refs['commodityFormRef'].resetFields();
      this.commodityForm.price = 0;
      this.commodityForm.describe = "";
    },
    submit() {
      request({
        url: "/commodity/addCommodity",
        method: "post",
        data: {
          commodityName: this.commodityForm.commodityName,
          commodityType: this.commodityForm.commodityType,
          price: this.commodityForm.price.toString(),
          count: this.commodityForm.count.toString(),
          describe: this.commodityForm.describe,
        },
      }).then((response) => {
        if (response.code === 200) {
          this.commodityID = response.data.commodityID;
          this.submitUpload();
          this.$tipUtil.successTip(response.msg);
        } else {
          this.$tipUtil.errTip(response.msg);
        }
      })
    }
  },
  setup() {
    const { appContext : { config: { globalProperties } } } = getCurrentInstance();
    const staticResourcesUrl = globalProperties.$staticResourcesUrl;
    return {
      staticResourcesUrl,
    }
  },
  mounted() {
    this.getCommodityType();
  }
}
</script>

<style scoped>
.add-commodity {
  height: 88vh;
  margin: 0;
  padding: 20px 0;
}
</style>